package com.imooc.luckymoney.luck;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 * The type Luckymoney controller.
 */
@RestController
public class LuckymoneyController {

    @Autowired
    private LuckymoneyRepository repository;

    @Autowired
    private LuckymoneyService service;

    @GetMapping("/luckymoneys")
    public List<Luckmoney> list() {
        return repository.findAll();
    }

    @PostMapping("/luckymoneys")
    public Luckmoney create(@RequestParam("producer") String producer,
                            @RequestParam("money") BigDecimal money) {
        Luckmoney luckmoney = new Luckmoney();
        luckmoney.setProducer(producer);
        luckmoney.setMoney(money);

        return repository.save(luckmoney);
    }

    @GetMapping("/luckymoneys/{id}")
    public Luckmoney findById(@PathVariable("id") Integer id) {
        return repository.findById(id).orElse(null);
    }

    @PutMapping("/luckymoneys/{id}")
    public Luckmoney update(@PathVariable("id") Integer id,
                            @RequestParam("consumer") String consumer) {
        Optional<Luckmoney> optional = repository.findById(id);
        if (optional.isPresent()){
            Luckmoney luckmoney = optional.get();
            // luckmoney.setId(id);
            luckmoney.setConsumer(consumer);
            return repository.save(luckmoney);
        }

        return null;
    }

    @PostMapping("/luckymoneys/two")
    public void createTwo(){
        service.createTwo();
    }
}
